<template>
  <div class="app-container">
    <el-row :gutter="6">
      <el-col :span="8">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <el-button v-permission="['Admin.Organization.Create']" type="primary" icon="el-icon-plus" @click="createOrganization()">添加顶级组织</el-button>
            <el-button type="default" icon="el-icon-refresh" style="float: right;" @click="refreshTree()">刷新</el-button>
          </div>
          <div style="overflow-x: hidden;">
            <ul id="treeOrganization" style="height:500px;" class="ztree ztreeMd"></ul>
          </div>
          <el-alert type="info" title="※鼠标移动到组织名称上，可对组织进行“添加下级组织”，“修改”，“删除”等操作"></el-alert>
          <el-alert type="info" title="※鼠标在组织名称上按住并拖动，可移动组织到任意位置"></el-alert>
          <el-alert type="info" title="※点击组织名称，右侧可显示当前组织下的人员列表"></el-alert>
          <el-alert type="info" title="※组织名称右侧的红色数字表示“当前组织及所有下级组织的人员总数量”"></el-alert>
          <el-alert type="info" title="※组织名称右侧的绿色数字表示“当前组织人员数量”"></el-alert>
        </el-card>
      </el-col>
      <el-col :span="16">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>组织成员</span>
          </div>
          <organization-unit-members ref="ouMembers"></organization-unit-members>
        </el-card>
      </el-col>
    </el-row>

    <edit-organization-unit-dialog ref="editOrganizationUnitDialog" @save="refreshTree()"></edit-organization-unit-dialog>
  </div>
</template>

<script>
import { getOrganizationUnits, moveOrganizationUnit, deleteOrganizationUnit } from "@/api/organization-unit";
import EditOrganizationUnitDialog from "./components/EditOrganizationUnitDialog";
import OrganizationUnitMembers from "./components/OrganizationUnitMembers";
import _ from "lodash";
import $ from "@/vendor/jquery";
import "ztree";
import "ztree/css/zTreeStyle/zTreeStyle.css";

const treeElementId = "treeOrganization";

export default {
  name: "OrganizationUnits",
  components: {
    "edit-organization-unit-dialog": EditOrganizationUnitDialog,
    "organization-unit-members": OrganizationUnitMembers
  },
  data() {
    return {
      moveModel: {
        newParentId: undefined,
        id: undefined
      },
      setting: {
        data: {
          simpleData: { enable: true },
          key: {
            name: "fullname",
            title: "name"
          }
        },
        view: {
          addHoverDom: this.addHoverDom,
          removeHoverDom: this.removeHoverDom,
          selectedMulti: false,
          nameIsHTML: true
        },
        edit: {
          drag: { isCopy: false },
          enable: true,
          removeTitle: "删除该组织",
          showRenameBtn: false
        },
        callback: {
          onClick: this.zTreeOnClick, // 点击
          beforeRemove: this.zTreeBeforeRemove, // 删除
          beforeDrop: this.zTreeBeforeDrop // 移动
        }
      }
    };
  },
  mounted() {
    this.initTree();
  },
  methods: {
    refreshTree() {
      this.initTree();
    },
    createOrganization(parentId) {
      this.$refs["editOrganizationUnitDialog"].show(undefined, parentId);
    },
    editOrganization(id) {
      this.$refs["editOrganizationUnitDialog"].show(id, undefined);
    },
    initTree() {
      const zNodes = [];
      getOrganizationUnits().then(result => {
        result.forEach(p => {
          zNodes.push({
            id: p.id,
            pId: p.parentId,
            name: p.displayName,
            fullname:
              p.displayName +
              '-----[<span style="color: rgb(245, 108, 108);">' +
              p.memberCountTotal +
              '</span>][<span style="color: rgb(103, 194, 58);">' +
              p.memberCount +
              "</span>]",
            code: p.code
          });
        });
        $.fn.zTree.init($("#" + treeElementId), this.setting, zNodes);
        const zTree = $.fn.zTree.getZTreeObj(treeElementId);
        const nodes = zTree.getNodes();
        this.expandNodes(zTree, nodes);
      });

      this.$refs["ouMembers"].show(undefined);
    },
    expandNodes(zTree, nodes) {
      if (!nodes) {
        return;
      }
      for (let i = 0, l = nodes.length; i < l; i++) {
        zTree.expandNode(nodes[i], true, false, false);
        if (nodes[i].isParent && nodes[i].zAsync && nodes[i].code.length < 5) {
          this.expandNodes(zTree, nodes[i].children);
        }
      }
    },
    addHoverDom(treeId, treeNode) {
      // 添加右侧按钮
      const treeNodeSelector = $("#" + treeNode.tId + "_span");
      if (treeNode.editNameFlag || $("#addBtn_" + treeNode.tId).length > 0) {
        return;
      }

      const editButtonStr = "<span class='button edit' id='editBtn_" + treeNode.tId + "' title='修改组织' onfocus='this.blur();'></span>";
      treeNodeSelector.after(editButtonStr);
      const editButton = $("#editBtn_" + treeNode.tId);
      if (editButton) {
        editButton.bind("click", () => {
          this.editOrganization(treeNode.id);
          return false;
        });
      }
      const addButtonStr = "<span class='button add' id='addBtn_" + treeNode.tId + "' title='添加下级组织' onfocus='this.blur();'></span>";
      treeNodeSelector.after(addButtonStr);
      const addButton = $("#addBtn_" + treeNode.tId);
      if (addButton) {
        addButton.bind("click", () => {
          this.createOrganization(treeNode.id);
          return false;
        });
      }
    },
    removeHoverDom(treeId, treeNode) {
      // 移除右侧按钮
      $("#addBtn_" + treeNode.tId)
        .unbind()
        .remove();
      $("#editBtn_" + treeNode.tId)
        .unbind()
        .remove();
    },
    zTreeOnClick(event, treeId, treeNode) {
      if (!treeNode) {
        return;
      }
      this.$refs["ouMembers"].show(treeNode.id);
    },
    zTreeBeforeRemove(treeId, treeNode) {
      // 删除节点事件
      const msg = '确定删除 "' + treeNode.name + '" 吗？删除后不可恢复！';
      this.$confirm(msg, "提示", { type: "warning" })
        .then(() => {
          deleteOrganizationUnit(_.parseInt(treeNode.id)).then(() => {
            this.$message({ message: "删除成功", type: "success" });
            this.refreshTree();
            return true;
          });
        })
        .catch(() => {
          return false;
        });
      return false;
    },
    moveOrganization(node, newParentNode) {
      const model = this.moveModel;
      let msg;
      if (newParentNode) {
        msg = '确定将 "' + node.name + '" 移动到 "' + newParentNode.name + '" 下吗？';
        model.id = node.id;
        model.newParentId = newParentNode.id;
      } else {
        msg = '确定将 "' + node.name + '" 移动到顶级吗？';
        model.id = node.id;
      }
      this.$confirm(msg, "提示", { type: "warning" })
        .then(() => {
          moveOrganizationUnit(model).then(() => {
            this.$message({ message: "移动成功", type: "success" });
            this.refreshTree();
            return true;
          });
        })
        .catch(() => {
          return false;
        });
    },
    zTreeBeforeDrop(treeId, treeNodes, targetNode, moveType) {
      // 移动节点事件
      if (!treeNodes) {
        return;
      }
      const node = treeNodes[0];
      let newParentNode = targetNode;

      if (moveType === "inner") {
        this.moveOrganization(node, newParentNode);
      } else {
        newParentNode = targetNode.getParentNode();
        if (newParentNode) {
          if (node.pId === newParentNode.id) {
            return false;
          } else {
            this.moveOrganization(node, newParentNode);
          }
        } else {
          this.moveOrganization(node, undefined);
        }
      }

      return false;
    }
  }
};
</script>
